<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShwoLoginMoadl(false)"></div>
    <!-- 登录box -->
    <div class="loginBox">
      <img src="../assets/img/close.png" class="close" @click="changeIsShwoLoginMoadl(false)" alt="" />
      <!-- 切换的内容 -->
      <section class="nav">
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true">手机号登录 </a> |
        <a href="#" :class="{ active: !isShowPhone }" @click="showWX">微信扫码登录 </a>
      </section>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机号  -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input type="text" placeholder="请输入手机号" v-model="PhoneNumber" class="ipt" />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" v-model="code" placeholder="请输入短信验证码" class="ipt" />
            <!--        <button class="btncode" @click="getCode">{{ isShowCount ? count + 's' : '获取验证码' }}</button> -->
            <button class="btncode" v-show="!isShowCount" @click="getCode">获取验证码</button>
            <button class="btncode" v-show="isShowCount">{{ count + 's' }}</button>
          </div>
          <div class="row">
            <button class="btnlogin ipt" @click="submitFn">登录</button>
          </div>
        </div>
        <!--扫码 -->
        <div class="qrLogin qrcode" id="weixin" v-show="!isShowPhone">11</div>
      </div>
    </div>
  </div>
</template>
 
<script>
import { mapMutations, mapActions } from 'vuex'
import { SendMSAPI, phoneReginAPI, bindingAPI } from '@/request/api'
import { validatePhoneNumber } from '@/utils'
export default {
  data() {
    return {
      isShowPhone: true,
      msg: '向右滑动',
      arr: [
        require('../assets/img/integral-01.9386d4bf.png'),
        require('../assets/img/integral-02.150d92a1.png'),
        require('../assets/img/integral-03.9870f3f1.png'),
        require('../assets/img/integral-04.afadcbdf.png')
      ],
      /* 手机号码 */
      PhoneNumber: '',
      count: 50,
      /*  */
      isShowCount: false,
      /* 验证码 */
      code: ''
    }
  },
  methods: {
    ...mapMutations({
      changeIsShwoLoginMoadl: 'showModal/changeIsShwoLoginMoadl',
      changeLoginMoadl: 'loginStatus/changeLoginMoadl',
      changeIsShowToastMoadl: 'showToast/changeIsShowToastMoadl'
    }),
    ...mapActions({
      asyncChangeToast: 'showToast/asyncChangeToast',
      asyncChangeUserInfo: 'userinfo/asyncChangeUserInfo'
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1)
      this.msg = 'login success, 耗时 ' + ms + 's'
    },
    // 拼图失败
    onFail() {
      this.onRefresh() // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = '再试一次'
    },
    daijishi() {
      /* 倒计时函数 的封装 */

      this.isShowCount = true

      let timer = setInterval(() => {
        this.count--
        if (this.count <= 0) {
          this.count = 50
          this.isShowCount = false
          clearInterval(timer)
        }
      }, 1000)
    },
    toVerify() {
      if (!validatePhoneNumber(this.PhoneNumber)) {
        // alert('请输入正确的手机号码')
        /* 使用Toast组件 */
        this.asyncChangeToast({
          isshow: true,
          msg: '请输入正确的手机号码',
          type: 'success'
        })
        // setTimeout(() => {
        //   this.changeIsShowToastMoadl({
        //     isshow: false
        //   })
        // }, 1000)
        return
      }
      if (this.msg == '再试一次' || this.msg == '向右滑动') {
        // alert('请滑动滑动验证码')
        this.asyncChangeToast({
          isshow: true,
          msg: '请滑动滑动验证码',
          type: 'danger'
        })
        return
      }
      /* 函数默认返回undefined */
      return true
    },
    /* 获取验证码  */
    async getCode() {
      /* 1判断手机号是否正确，不正确提示 */
      // let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      // /* 取反判断 */
      // if (!reg.test(this.PhoneNumber)) {
      //   alert('请输入正确的手机吗')
      //   return
      // }
      // /* 2滑动验证码不正确提示 */
      // if (this.msg == '再试一次' || this.msg == '向右滑动') {
      //   alert('请滑动滑动验证码')
      //   return
      // }
      /* 3获取 验证码  60s 倒计时功能
        获取验证码  发请深圳市
        侄计时 循环递减减数字   count
      */
      /* 看正则和滑块返回的是什么  如果是undefined 取反，就进行return   */
      let flag = this.toVerify()
      // console.log(flag)
      if (!flag) return //不通过就不往下执行
      let res = await SendMSAPI({
        phone: this.PhoneNumber
      })
      // console.log('发送短信验证码：', res)
      /* 响应处理 */
      if (!res) return
      alert('发送成功')
      this.daijishi()
      // if (res.data.code == 400) {
      //   this.daijishi()
      // }
    },
    async submitFn() {
      //手机号码不正确提示
      //滑块不正确提示
      if (!this.toVerify()) return
      //验证码不为空
      if (!this.code.trim()) {
        alert('验证码不能为空')
        return
      }
      /* 发起登录请求 */
      //有uuid就是关联微信   没有就是普通手机号验证码登录
      let uuid = localStorage.getItem('uuid')
      let res = null
      if (uuid) {
        res = await bindingAPI({
          verifyCode: this.code,
          phone: this.PhoneNumber,
          uuid
        })
      } else {
        res = await phoneReginAPI({
          verifyCode: this.code,
          phone: this.PhoneNumber
        })
      }

      // console.log(res)
      if (!res) return

      //提示
      alert('登录成功')
      //存储token            obj['a']  obj.a
      localStorage.setItem('x-auth-token', res['x-auth-token'])
      //关闭模态框
      /* 修改store中的状态的值   让登录这个按钮隐藏 */
      this.changeLoginMoadl(true)
      this.changeIsShwoLoginMoadl(false)
      /* 绑定1   清除code  重新跳转到该页面 */
      uuid && this.$router.push(this.$route.path)
      localStorage.removeItem('uuid')
      /* 获取用户信息并更新vuex */
      this.asyncChangeUserInfo()
      //topbar中登录状态的切换

      /* 布局一个购物车按钮 
        vuex中loginStatus存储一个isLogined （是否登录 的状态
        根据isLogined 来控制购物车按钮是否显示 
          本地有token isLogined 则为true   本地无token 
      */
    },
    //获取二维码 并展示
    showWX() {
      // 申请微信登录二维码
      this.isShowPhone = false
      let _this = this
      new WxLogin({
        id: 'weixin',
        appid: 'wx67cfaf9e3ad31a0d', // 这个appid要填死
        scope: 'snsapi_login',
        // 扫码成功后重定向的接口
        redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
        // state填写编码后的url
        state: encodeURIComponent(window.btoa('http://127.0.0.1:8080' + _this.$route.path)),
        // 调用样式文件
        href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICBkaXNwbGF5OiBub25lOw0KfSAgICANCi5pbXBvd2VyQm94IHFyY29kZXsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0='
      })
    }
  }
}
</script>
 
<style lang = "less" scoped>
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url('../assets/img/login-box-bg.png');
    .close {
      position: absolute;
      right: 70px;
      top: 40px;
    }
  }
  .nav {
    padding-top: 50px;
    text-align: center;

    a {
      text-decoration: none;
      color: gray;
      &.active {
        color: #000;
      }
    }
  }
  .content {
    background: pink;
    width: 355px;
    height: 300px;
    margin: 10px auto 0;
    /* 登录样式 */
    .row {
      display: flex;
      margin-bottom: 20px;
      .ipt {
        height: 50px;
        outline: none;
        flex: 1;
        text-indent: 1em;
      }
      .btncode {
        background-color: #0a328e;
        color: #fff;
        width: 100px;
      }
      .btnlogin {
        background-color: #0a328e;
        color: #fff;
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>